package com.tnl.hunter.webchat.controller;

import com.biz.hunter.dao.EmployerDAO;
import com.biz.hunter.dao.HunterDAO;
import com.biz.hunter.dao.WXUserDAO;
import com.biz.hunter.db.entity.Employer;
import com.biz.hunter.db.entity.Hunter;
import com.biz.system.config.QiNiuConfig;
import com.biz.wechat.annotation.OAuthRequired;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

// 服务文件，上载的简历、音频
@Controller
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private WXUserDAO userDAO;

    @Autowired
    private EmployerDAO employerDAO;

    @Autowired
    private HunterDAO hunterDAO;

    public static final String BASE_PATH = "/usr/share/tomcat/uploads/";


    //public static final String BASE_PATH = "d:/";
//	public static final String BASE_PATH = "C:\\Projects\\weixin\\bak\\image\\";

    @OAuthRequired
    @RequestMapping(value = "/rs/{fileName}.{ext}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(@PathVariable("fileName") String fileName, @PathVariable("ext") String fileExt) throws IOException {

        File downloadFile = new File(BASE_PATH + fileName + "." + fileExt);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //APPLICATION_OCTET_STREAM是以流的形式下载文件，这样可以实现任意格式的文件下载。
        headers.setContentDispositionFormData("attachment", fileName + "." + fileExt);

        // return new ResponseEntity<byte[]>(
        // FileUtils.readFileToByteArray(downloadFile), headers,
        // HttpStatus.CREATED);
        //网上有些人把HttpStatus.OK改成了HttpStatus.CREATED，这样在IE下会有问题，无法下载文件。
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.OK);
    }

    @OAuthRequired
    @RequestMapping(value = "/rs/audio/{fileName}.{ext}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> playAudio(@PathVariable("fileName") String fileName, @PathVariable("ext") String fileExt) throws IOException {

        File downloadFile = new File(BASE_PATH + fileName + "." + fileExt);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("audio/amr")); //APPLICATION_OCTET_STREAM是以流的形式下载文件，这样可以实现任意格式的文件下载。
//    headers.setContentDispositionFormData("attachment", fileName + "." + fileExt); 
        //header(’Content-type: audio/amr’);
//    headers.setPr);

        // return new ResponseEntity<byte[]>(
        // FileUtils.readFileToByteArray(downloadFile), headers,
        // HttpStatus.CREATED);
        //网上有些人把HttpStatus.OK改成了HttpStatus.CREATED，这样在IE下会有问题，无法下载文件。
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.OK);
    }


    @OAuthRequired
    @RequestMapping(value = "/rs/pdf/{fileName}.{ext}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> displayPDF(@PathVariable("fileName") String fileName, @PathVariable("ext") String fileExt) throws IOException {

        File downloadFile = new File(BASE_PATH + fileName + "." + fileExt);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA); //APPLICATION_OCTET_STREAM是以流的形式下载文件，这样可以实现任意格式的文件下载。
        headers.setContentDispositionFormData("attachment", fileName + "." + fileExt);
        //header(’Content-type: audio/amr’);
//	    headers.setPr);

        // return new ResponseEntity<byte[]>(
        // FileUtils.readFileToByteArray(downloadFile), headers,
        // HttpStatus.CREATED);
        //网上有些人把HttpStatus.OK改成了HttpStatus.CREATED，这样在IE下会有问题，无法下载文件。
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(downloadFile), headers, HttpStatus.OK);
    }


    @RequestMapping(value = "/rs/img/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> upload(@RequestParam("file") MultipartFile file, @RequestParam("type") String type, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String openid = (String) session.getAttribute("OpenId");
//        openid = "o852Is7CAaACPsK06dWq5NUKlC-o";
        logger.debug("openid is " + openid);
        Map<String,String> map = new HashMap<>();
        if (!StringUtils.hasText(openid)) {
            map.put("errorcode", "40001");
            map.put("msg", "必须在微信平台使用我们的服务");
            return map;
        }


        String fileName=file.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        // 指定路径
        String path =request.getSession().getServletContext().getRealPath("/") + File.separator + "upload" + File.separator;
        FileOutputStream fos;
        //重命名
        String newFileName= UUID.randomUUID().toString() + fileName.hashCode() + suffix;//避免冲突
        String filePath=path +  File.separator + newFileName;
        System.out.println(filePath);
        try {
            fos = FileUtils.openOutputStream(new File(filePath));
            IOUtils.copy(file.getInputStream(), fos);
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//
        String fileNamePath = uploadFile(filePath, fileName, QiNiuConfig.BUCKET_MEDTREND, 2);
        fileNamePath = QiNiuConfig.FILE_PREFIX_PATH + fileNamePath;
        if (Objects.equals("hr", type)){
            Employer employer = employerDAO.getByOpenId(openid);
            employer.setHeadImgUrl(fileNamePath);
            employerDAO.update(employer);
        }else{
            Hunter hunter = hunterDAO.getByOpenId(openid);
            hunter.setHeadImgUrl(fileNamePath);
            hunter.setImageUrl(fileNamePath);
            hunterDAO.update(hunter);
        }
        map.put("file",fileNamePath);
        map.put("code", "200");
        return map;
    }


    public static String uploadFile(String filePath, String fileName, String bucketName, int zoneName) {
        try {
            Zone zone = Zone.zoneNa0();
            if (zoneName == 0) {// 华南
                zone = Zone.zone0();
            }
            if (zoneName == 1) {// 华北
                zone = Zone.zone0();
            }
            if (zoneName == 2) { // 华东
                zone = Zone.zone0();
            }

            Configuration cfg = new Configuration(zone);
            UploadManager uploadManager = new UploadManager(cfg);
            Response response = uploadManager.put(filePath, fileName, token(bucketName));
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.info(fileName + "----文件上传失败----" + r.toString());
            try {
                System.err.println(r.bodyString());
                logger.info(fileName + "----文件上传失败----" + r.toString());
            } catch (QiniuException ex2) {
                // ignore
            }
            return null;
        }
    }


    /**
     * 默认存储空间
     *
     * @param bucketName
     * @return
     */
    public static String token(String bucketName) {
        Auth auth = Auth.create(QiNiuConfig.QNACCESS_KEY, QiNiuConfig.QNSECRET_KEY);
        String upToken = auth.uploadToken(bucketName);
        return upToken;
    }

}
